//
//  CZHTTPClient.swift
//  Weibo24
//
//  Created by apple on 16/3/8.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import AFNetworking

enum CZHTTPClientType: Int{

    case POST = 0
    case GET = 1
    
}

class CZHTTPClient: AFHTTPSessionManager {

    // 创建一个网络请求类单例
    static let shareInstance: CZHTTPClient = {
    
        let client = CZHTTPClient()
        
        // 修改一些属性
        client.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return client
    }()
    
    //对外提供一个方法, 这个方法 即支持Post 也支持 Get
    
    /*
        如何区分 Get 和Post
    
    override func GET(URLString: String, parameters: AnyObject?, progress downloadProgress: ((NSProgress) -> Void)?, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure: ((NSURLSessionDataTask?, NSError) -> Void)?) -> NSURLSessionDataTask? {
    
    }
   
    
    override func POST(URLString: String, parameters: AnyObject?, progress uploadProgress: ((NSProgress) -> Void)?, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure: ((NSURLSessionDataTask?, NSError) -> Void)?) -> NSURLSessionDataTask? {
    
    }
    */
    /*
        AnyObject 是一个协议,所有的类 遵守这个协议. AnyObject 是swift
       NSObject , 是OC里
    */
    
    func RequestData(type: CZHTTPClientType,URLString: String, parameters: AnyObject?,success: (JSON: AnyObject?)->(),failure: (error: NSError)->()){
    
        if type == .GET{
        
            self.GET(URLString, parameters: parameters, progress: nil, success: { (_ , JSON) -> Void in
                
                //先处理一下JSON
                // 网络请求底部,进行的转换, 顶层使用的时候,直接就是字典
//                if let json = JSON as? [String:NSObject]{
//                
//                }
                
                //回调
                    success(JSON: JSON)
                
                
                }, failure: { (_ , error) -> Void in
                    failure(error: error)
            })
            
        } else {
        
            self.POST(URLString, parameters: parameters, progress: nil, success: { (_ , JSON) -> Void in
                success(JSON: JSON)
                }, failure: { (_ , error) -> Void in
                    failure(error: error)
            })
            
        }
        
    }
}


